const express = require('express');
const router = express.Router();
const db = require('../config/db');
function checkLogin(req, res, next) {
    if (req.session.user) {
        next();
    } else {
        res.status(401).send('Unauthorized');
    }
}
router.get('/get-items', checkLogin, (req, res) => {
    const userId = req.session.user.id;
    db.query('SELECT c.id, p.name, p.price, c.quantity FROM cart c JOIN products p ON c.product_id = p.id WHERE c.user_id = ?', [userId], (err, results) => {
        if (err) throw err;
        res.json(results);
    });
});
router.post('/clear', checkLogin, (req, res) => {
    const userId = req.session.user.id;
    db.query('DELETE FROM cart WHERE user_id = ?', [userId], (err, result) => {
        if (err) throw err;
        res.json({ success: true });
    });
});
router.post('/add', checkLogin, (req, res) => {
    const userId = req.session.user.id;
    const { productId } = req.body;
    db.query('SELECT * FROM cart WHERE user_id = ? AND product_id = ?', [userId, productId], (err, results) => {
        if (err) throw err;
        if (results.length > 0) {
            db.query('UPDATE cart SET quantity = quantity + 1 WHERE user_id = ? AND product_id = ?', [userId, productId], (err, result) => {
                if (err) throw err;
                res.json({ success: true });
            });
        } else {
            db.query('INSERT INTO cart (user_id, product_id, quantity) VALUES (?, ?, 1)', [userId, productId], (err, result) => {
                if (err) throw err;
                res.json({ success: true });
            });
        }
    });
});

module.exports = router;